package com.testdocs.client.common.dialog.confirm;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.testdocs.client.common.i18n.CommonConstants;

public class ConfirmDialog {
	private static ConfirmDialogUiBinder uiBinder = GWT
			.create(ConfirmDialogUiBinder.class);

	@UiTemplate("ConfirmDialog.ui.xml")
	interface ConfirmDialogUiBinder extends
			UiBinder<Widget, ConfirmDialog> {
	}

	ActionConfirmedHandler handler;
	
	@UiField
	DialogBox dialogBox;
	@UiField
	Label messageLabel;
	
	@UiField
	Button okButton;
	@UiField
	Button cancelButton;
	
	private CommonConstants commonConstants = (CommonConstants) GWT.create(CommonConstants.class);
	
	public ConfirmDialog(String caption, String message) {
		uiBinder.createAndBindUi(this);
		okButton.setText(commonConstants.ok());
		cancelButton.setText(commonConstants.cancel());
		
		dialogBox.setText(caption);
		messageLabel.setText(message);
	}

	public ConfirmDialog(ActionConfirmedHandler handler) {
		this();
		this.handler = handler;
	}

	public ConfirmDialog() {
		this("", "");
	}

	private void show() {
		dialogBox.center();
		dialogBox.show();
		
		cancelButton.setFocus(true);
	}

	public void show(ActionConfirmedHandler handler) {
		this.handler = handler;
		show();
}
	
	public void show(String caption, String message, ActionConfirmedHandler handler) {
		dialogBox.setText(caption);
		messageLabel.setText(message);
		show(handler);
	}
	
	public void show(String caption, String message) {
		dialogBox.setText(caption);
		messageLabel.setText(message);
		show();
	}

	@UiHandler("cancelButton")
	void handleCancel(ClickEvent e) {
		hide();
	}

	@UiHandler("okButton")
	void handleOk(ClickEvent e) {
		hide();
		handler.handle();
	}

	public void hide() {
		dialogBox.hide();
	}
	
	public interface ActionConfirmedHandler extends EventHandler {
		public void handle();
	}
}
